<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 分组管理
 *
 * @author      Eden
 * @datetime    2016/12/13 00:53
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Group_Model extends ADM_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 获取列表
     * @return bool
     */
    public function getLists()
    {
        try {
            $q = $this->db->order_by('id', 'DESC')->get('stream_group');
            return $q->result_array();
        } catch(PDOException $e) {}
        return false;
    }

    /**
     * 添加分组
     * @param $gName
     * @return array|bool
     */
    public function addGroup($gName)
    {
        $db = clone($this->db);
        $q = $db->get_where('stream_group', array('groupName' => $gName));
        if ($q->row_array()) {
            $this->setError('该分组已存在');
            return false;
        }

        $data = array(
            'groupName' => $gName,
            'deviceNum' => 0
        );

        $this->db->insert('stream_group', $data);
        if ($id = $this->db->insert_id()) {
            return array_merge($data, array('id' => $id));
        } else {
            return false;
        }
    }

    /**
     * 修改
     * @param $gid
     * @param $gName
     * @return bool
     */
    public function editGroup($gid, $gName)
    {
        $db = clone($this->db);
        $q = $db->get_where('stream_group', array('id' => $gid));
        if (!$q->row_array()) {
            $this->setError('该分组已存在');
            return false;
        }

        $data = array(
            'groupName' => $gName
        );

        $this->db->where('id', $gid);
        $this->db->update('stream_group', $data);
        if ($id = $this->db->affected_rows()) {
            return true;
        } else {
            return false;
        }
    }

    public function deleteGroup($gid)
    {
        $db = clone($this->db);
        $q = $db->get_where('stream_group', array('id' => $gid));
        $r = $q->row_array();
        if ($r && $r['deviceNum'] > 0) {
            $this->setError('该分组下包含设备,请勿删除');
            return false;
        }

        if ($gid == 1) {
            $this->setError('默认分组,请勿删除');
            return false;
        }

        $this->db->where('id', $gid);
        $this->db->delete('stream_group');
        if ($id = $this->db->affected_rows()) {
            return true;
        } else {
            return false;
        }
    }
}
